# -*- coding: utf-8 -*-
# 引入webdriver和单元测试框架unittest
from selenium import webdriver
import unittest, time, re
# 引入HTMLTestRunner包，非标准库
import HTMLTestRunner

class Baidu(unittest.TestCase):
    # 初始化设置,自动执行；
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)
        self.base_url = "http://www.baidu.com/"
        self.verificationErrors = []
        self.accept_next_alert = True

    # 自动化用例区域
    def test_01_baidu_search(self):
        driver = self.driver
        driver.get(self.base_url)
        driver.find_element_by_id("kw").click()
        driver.find_element_by_id("kw").clear()
        driver.find_element_by_id("kw").send_keys("Selenium Webdriver")
        driver.find_element_by_id("su").click()
        time.sleep(3)
        self.assertEqual(driver.title, u"Selenium Webdriver_百度搜索")

    #清理方法，自动执行；
    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)


if __name__ == "__main__":
    # 定义一个测试容器
    test = unittest.TestSuite()

    # 将测试用例，加入到测试容器中
    test.addTest(Baidu("test_01_baidu_search"))

    # 定义个报告存放的路径，支持相对路径
    now = time.strftime("%Y-%m-%M-%H-%M-%S", time.localtime(time.time()))
    file_path = "file/result"+now+".html"
    file_result = open(file_path, 'wb')

    # 定义测试报告
    runner = HTMLTestRunner.HTMLTestRunner(stream=file_result, title=u"百度搜索测试报告", description=u"用例执行情况")

    # 运行测试用例
    runner.run(test)
    file_result.close()